package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.proditem.service.GetProductInfoByProductIdCall;
import com.ymatou.iapi.productmanager.service.ActivityProductStartSaleCall;
import com.ymatou.iapi.productmanager.service.ActivityProductSuspendSaleCall;
import com.ymatou.iapi.productmanager.service.RemoveProductFromLiveCall;
import com.ymatou.iapi.productmanager.service.SaveProductTemplateCall;
import com.ymatou.iapi.productmanager.service.SetPspTagCall;
import com.ymatou.iapi.productmanager.service.SetTopProductCall;
import com.ymatou.iapi.productmongosync.service.EsCall;
import com.ymatou.iapi.productsync.service.InvokemongocrudCall;
import com.ymatou.iapi.productviolate.service.GetProductViolateRemarksCall;
import com.ymatou.iapi.selleractivity.service.ApplyActivityCall;
import com.ymatou.iapi.sellerproduct.parameter.BrandBean;
import com.ymatou.iapi.sellerproduct.parameter.CatalogLevelBean;
import com.ymatou.iapi.sellerproduct.parameter.ProdTplBean;
import com.ymatou.iapi.sellerproduct.service.AddFbxProductCall;
import com.ymatou.iapi.sellerproduct.service.AddNewSellerProductCall;
import com.ymatou.iapi.sellerproduct.service.AddProductInLivesCall;
import com.ymatou.iapi.sellerproduct.service.BatchDeleteProductsCall;
import com.ymatou.iapi.sellerproduct.service.BatchSetProductOffSaleCall;
import com.ymatou.iapi.sellerproduct.service.BatchSetProductOnSaleCall;
import com.ymatou.iapi.sellerproduct.service.ChangeNewProductInfoCall;
import com.ymatou.iapi.sellerproduct.service.GetSetTopProductsCall;
import com.ymatou.iapi.sellerproduct.service.QuerySellerProductListCall;
import com.ymatou.iapi.sellerproduct.service.SaveCatalogPackageListCall;
import com.ymatou.iapi.sellerproduct.service.UpdateProductCatalogsCall;
import com.ymatou.iapi.trading.operate.parameter.OrderItemVo;
import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.ProductRefundChannelEnum;
import com.ymt.core.tool.Logger;
import com.ymttest.database.model.SpuProperty;
import com.ymttest.database.model.YmtProductDescExtra;
import com.ymttest.database.model.YmtProductsI;
import com.ymttest.database.model.YmtProductsInActivity;
import com.ymttest.database.mongo.ProductDescExtraWapper;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.ProductDescExtraNewWapper;
import com.ymttest.database.mongo.jproduct.ProductsWapper;
import com.ymttest.database.sqlwapper.SpuPropertyWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.database.sqlwapper.YmtProductActivityStockWapper;
import com.ymttest.database.sqlwapper.YmtProductBrandWapper;
import com.ymttest.database.sqlwapper.YmtProductCategoryWapper;
import com.ymttest.database.sqlwapper.YmtProductDescExtraWapper;
import com.ymttest.database.sqlwapper.YmtProductDescMapWapper;
import com.ymttest.database.sqlwapper.YmtProductPictureWapper;
import com.ymttest.database.sqlwapper.YmtProductPropertyWapper;
import com.ymttest.database.sqlwapper.YmtProductsIWapper;
import com.ymttest.database.sqlwapper.YmtProductsInActivityWapper;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.constant.JsonBeanFile;

public class SellerProductCallService {
	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss");
	private static SimpleDateFormat sdfForName = new SimpleDateFormat(
			"MM-dd HH:mm:ss");

	
	
	public static JSONObject addProduct(JSONObject jsonBean) {
		AddNewSellerProductCall addNewSellerProductCall = new AddNewSellerProductCall();
		JSONObject ret = addNewSellerProductCall.callAndGetReturnData(jsonBean);
		try {
			String productId = ret.getJSONObject("Data").getString("ProductID");
			new ProductsWapper().getByProductId(productId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ret;
	}
	
	
	public static void setProductPsp(String productId, boolean isPsp){
		new SetPspTagCall().call(3383, productId, isPsp);
	}
	
	
	
	public static ProdTplBean saveTemplate(int sellerId,int templateTypeId)throws JSONException {
		return saveTemplate(sellerId,templateTypeId,null);
	}
	public static ProdTplBean saveTemplate(int sellerId,int templateTypeId,Map<String, Object> updateMap) throws JSONException{
		Map<String, Object> map = MapUtil.hashMap();
		
		if (updateMap!=null && updateMap.size()>0){map.putAll(updateMap);}
		
		map.put("SellerId", sellerId);
		map.put("TemplateType", templateTypeId);
		String p1 = "http://pic1.ymatou.com/G01/shangou/M00/31/92/rBB"+Calendar.getInstance().getTimeInMillis()+".jpg";
		String p2 = "http://pic1.ymatou.com/G01/shangou/M00/22/92/rBB"+Calendar.getInstance().getTimeInMillis()+".jpg";
		map.put("PicUrls", new JSONArray(Arrays.asList(p1,p2)));
		
		JSONObject jsonData = new SaveProductTemplateCall().callAndGetReturnData(map);
		JSONObject requestData = jsonData.getJSONObject("JsonBeanRequest");
		
		ProdTplBean prodTplBean = new ProdTplBean();
		prodTplBean.setTemplateId(jsonData.getJSONObject("Data").getInt("ProductTemplateId"));
		prodTplBean.setTemplateSellerId(requestData.getInt("SellerId"));
		prodTplBean.setTemplateName(requestData.getString("TemplateName"));
		prodTplBean.setTemplateDesc(requestData.getString("Description"));
		prodTplBean.setTemplateType(requestData.getInt("TemplateType"));
		
		JSONArray picArray = requestData.getJSONArray("PicUrls");
		List<String> picList = new ArrayList<>();
		for(int i=0;i<picArray.length();i++){picList.add(picArray.getString(i));}
		prodTplBean.setPicUrls(picList);
		
		return prodTplBean;
	
	}
	
	
	public static int deleteTemplate(int sellerId){
		Logger.comment("删除模板   sellerID:"+sellerId);
		YmtProductDescExtraWapper ymtProductDescExtraWapper = new YmtProductDescExtraWapper();
		return ymtProductDescExtraWapper.deleteTemplate(sellerId);
	}
	
	
	
	public static List<String> getProductViolateTips(String productId) throws JSONException{
		List<String> retTips = new ArrayList<>();
		
		JSONObject ret = new GetProductViolateRemarksCall().call(Arrays.asList(productId));
		if (ret.getJSONObject("Result").isNull("ViolateItems")){
			return retTips;
		}
		JSONArray ViolateItems = ret.getJSONObject("Result").getJSONArray("ViolateItems");
		for (int i=0;i<ViolateItems.length();i++){
			if (ViolateItems.getJSONObject(i).getString("ProductId").equals(productId)){
				retTips.add(ViolateItems.getJSONObject(i).getString("ViolateBussinessRule"));
			}
		}
		return retTips;
	
	}
	
	
	public static OrderItemVo getOrderItemVo(String productId, String catalogId) {
		OrderItemVo orderItemVo = new OrderItemVo();
		try {
			JSONObject productInfo = GetProductInfoByProductIdCall
					.GetProductInfoByProductId(productId).getJSONObject("Data")
					.getJSONObject("Product");
			JSONArray catalogInfoAry = productInfo.getJSONArray("CatalogList");
			JSONObject catalogInfo = new JSONObject();
			for (int i = 0; i < catalogInfoAry.length(); i++) {

				//catalogId =null，默认去第一个商品规格
				if (null == catalogId) {
					catalogInfo = catalogInfoAry.getJSONObject(0);
					catalogId = catalogInfo.getString("CatalogId");

					break;
				}

				if (catalogInfoAry.getJSONObject(i).getString("CatalogId")
						.equals(catalogId)) {
					catalogInfo = catalogInfoAry.getJSONObject(i);

					break;
				}
			}
			orderItemVo.setProductId(productId);
			orderItemVo.setCatalogId(catalogId);

			orderItemVo.setSellerId(productInfo.getInt("SellerId"));
			orderItemVo.setProductName(productInfo.getString("Title"));
			orderItemVo.setPictureUrl(productInfo.getJSONArray("PicList")
					.getString(0));
			orderItemVo.setBrandId(productInfo.getInt("BrandId"));
			orderItemVo.setTariffType(productInfo.getInt("TariffType"));
			orderItemVo.setSupportsRtnWithoutReason(productInfo
					.getBoolean("NoReasonReturn"));
			orderItemVo.setProductRecordNo(productInfo.getString("ProdId"));
			orderItemVo.setPspProduct(productInfo.getBoolean("IsPspProduct"));

			orderItemVo.setThirdCategoryId(productInfo
					.getInt("ThirdCategoryId"));
			orderItemVo.setSecondCategoryId(productInfo.getInt("CategoryId"));
			orderItemVo.setFirstCategoryId(productInfo
					.getInt("MasterCategoryId"));
			orderItemVo
					.setFreightFree(productInfo.getBoolean("IsFreeShipping"));
			orderItemVo.setProductVer(productInfo.getString("Version"));

			orderItemVo.setProductPrice(BigDecimal.valueOf(catalogInfo
					.getDouble("Price")));
			orderItemVo.setSku(catalogInfo.getString("SKU"));
			orderItemVo.setPreSale(catalogInfo.getBoolean("IsPreSale"));

			String property = "";
			JSONArray propertyList = catalogInfo.getJSONArray("PropertyList");
			for (int i = 0; i < propertyList.length(); i++) {
				String name = propertyList.getJSONObject(i).getString("Name");
				String value = propertyList.getJSONObject(i).getString("Value");
				if (i == propertyList.length() - 1) {
					property = property + name + ":" + value;
				} else {
					property = property + name + ":" + value + ",";
				}
			}
			orderItemVo.setProperty(property);

			int localReturn = productInfo.getInt("LocalReturn");
			if (localReturn == 0) {
				orderItemVo
						.setProductRefundChannel(ProductRefundChannelEnum.None);
			} else if (localReturn == 1) {
				orderItemVo
						.setProductRefundChannel(ProductRefundChannelEnum.Official);
			} else if (localReturn == 2) {
				orderItemVo
						.setProductRefundChannel(ProductRefundChannelEnum.Seller);
			} else {
				orderItemVo
						.setProductRefundChannel(ProductRefundChannelEnum.None);
			}

			int deliveryMethod = productInfo.getInt("DeliveryMethod");
			if (deliveryMethod == 1) {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.China);
			} else if (deliveryMethod == 2) {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.US);
			} else if (deliveryMethod == 3) {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.SailProtect);
			} else if (deliveryMethod == 4) {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.BondedDelivery);
			} else if (deliveryMethod == 5) {
				orderItemVo
						.setLogisticsType(LogisticsTypeEnum.XloboBondedDelivery);
			} else if (deliveryMethod == 6) {
				orderItemVo
						.setLogisticsType(LogisticsTypeEnum.AuthenticatedDirectDelivery);
			} else if (deliveryMethod == 7) {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.PackageDelivery);
			} else {
				orderItemVo.setLogisticsType(LogisticsTypeEnum.Unknown);
			}
			return orderItemVo;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return orderItemVo;
	}
	/***
	 * 修改所有规格库存为0
	 */
	public static void updateAllStockNumAs0(int sellerId, String productId)
			throws Exception {
		new YmtCatalogsIWapper().selectCatalogsByProductId(productId)
				.forEach(
						prodInfo -> {
							String catalogId = prodInfo.getsCatalogId();
							try {
								updateProductStockNum(sellerId, productId,
										catalogId, 0);
							} catch (Exception e) {
								e.printStackTrace();
							}
						});
	}
	
	
	
	public static void updateActivityStockNumAs0(int sellerId, String productId)
			throws Exception {
		YmtProductActivityStockWapper ymtProductActivityStockWapper = new YmtProductActivityStockWapper();
		
		List<Integer> aids = ymtProductActivityStockWapper.selectByProductId(productId).stream().map(x->x.getIactivityid()).collect(Collectors.toList());
		aids.forEach(aid->ymtProductActivityStockWapper.updateStockByActivityIdAndProductId(productId, aid, 0));
		
		
		List<Integer> inaids = ymtProductActivityStockWapper.selectByProductId(productId).stream().map(x->x.getIproductinactivityid()).collect(Collectors.toList());
		inaids.forEach(inaid->{
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				new InvokemongocrudCall().callAndGetReturnData(inaid, productId, "SyncActivityProduct");
			}
			
			if (YmtMongoDriverFactroy.isEsCheck()){
				new EsCall().callAndGetReturnData(inaid, productId, "SyncActivityProduct");
			}
		});
	}
	
	
	
	
	
	public static JSONObject batchDeleteProduct(int sellerId,List<String> productList) throws Exception {
		return new BatchDeleteProductsCall().callAndGetReturnData(MapUtil.hashMap("UserID", sellerId,"ProductIds",new JSONArray(productList)));
	}
	
	

	/***
	 * 修改商品库存
	 * @param sellerId
	 * @param prodId
	 * @param catalogId
	 * @param num
	 * @return
	 * @throws Exception
	 */
	public static boolean updateProductStockNum(int sellerId, String prodId,
			String catalogId, int num) throws Exception {
		UpdateProductCatalogsCall updateProductCatalogsCall = new UpdateProductCatalogsCall();
		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("Catalogs[0]->UserId", sellerId);
		updateMap.put("UserID", sellerId);
		updateMap.put("ProductID", prodId);
		updateMap.put("Catalogs[0]->CatalogId", catalogId);
		updateMap.put("Catalogs[0]->Num", num);

		return updateProductCatalogsCall.callAndGetReturnData(updateMap)
				.get("Code").toString().equals("200");
	}

	/***
	 * 移出橱窗中所有商品
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public static boolean removeAllProductInTop(int userId) throws Exception {
		//1 get top list
		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("UserId", userId);
		GetSetTopProductsCall getSetTopProductsCall = new GetSetTopProductsCall();
		JSONObject toplistObj = getSetTopProductsCall
				.callAndGetReturnData(updateMap);
		JSONArray products = toplistObj.getJSONObject("Data").getJSONArray(
				"Products");

		List<String> productListInTop = new ArrayList<String>();
		for (int i = 0; i < products.length(); i++) {
			productListInTop.add(products.getJSONObject(i).getString(
					"ProductId"));
		}

		//2 clear product in top list
		Map<String, Object> updateTopMap = new HashMap<String, Object>();
		updateTopMap.put("UserId", userId);
		updateTopMap.put("UserId", userId);
		updateTopMap.put("ProductIds",
				new JSONArray(productListInTop.toString()));
		updateTopMap.put("IsSetTop", false);
		new SetTopProductCall().callAndGetReturnData(updateTopMap);

		//3 check again
		return getSetTopProductsCall.callAndGetReturnData(updateMap)
				.getJSONObject("Data").getJSONArray("Products").length() == 0;
	}

	/***
	 * 添加商品到橱窗 
	 * @param sellerId
	 * @param productIds
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addProductsIntoTopList(int sellerId,
			List<String> productIds) throws Exception {
		Map<String, Object> updateTopMap = new HashMap<String, Object>();
		updateTopMap.put("UserId", sellerId);
		updateTopMap.put("ProductIds", new JSONArray(productIds.toString()));
		updateTopMap.put("IsSetTop", true);

		return new SetTopProductCall().callAndGetReturnData(updateTopMap);

	}

	/***
	 * 移出商品出橱窗
	 * @param sellerId
	 * @param productIds
	 * @return
	 * @throws Exception
	 */
	public static JSONObject removeProductsFromTopList(int sellerId,
			List<String> productIds) throws Exception {
		Map<String, Object> updateTopMap = new HashMap<String, Object>();
		updateTopMap.put("UserId", sellerId);
		updateTopMap.put("ProductIds", new JSONArray(productIds.toString()));
		updateTopMap.put("IsSetTop", false);

		return new SetTopProductCall().callAndGetReturnData(updateTopMap);

	}

	/***
	 * 通过 productId 和sellerId 查询商品
	 * @param sellerId
	 * @param productId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 */
	public static JSONObject queryProduct(String sellerId, String productId)
			throws ClientProtocolException, IOException, JSONException {
		QuerySellerProductListCall querySellerProductListCall = new QuerySellerProductListCall();

		JSONObject queryProductBean = JsonBeanHelper
				.getJsonBean(JsonBeanFile.QuerySellerProductListTpl);
		JsonBeanHelper.updateJsonBean(queryProductBean, "ProductIdList",
				new JSONArray("[" + productId + "]"));
		JsonBeanHelper.updateJsonBean(queryProductBean, "SellerId", sellerId);

		querySellerProductListCall.setData(queryProductBean);
		querySellerProductListCall.callService();

		return new JSONObject(querySellerProductListCall.getReturnData());

	}

	/***
	 * 发布商品为定时上架
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProductOnTime(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 1);
		map.put("Product->ProductName",
				"自动化测试_定时上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		//定时为未来5天上架
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, 5);
		map.put("Product->ValidStart", sdf.format(c.getTime()));

		c.add(Calendar.DAY_OF_MONTH, 13);
		map.put("Product->ValidEnd", sdf.format(c.getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);

	}

	
	public static JSONObject addNewProductAsPackage(int sellerId,String sellerName,Map<String,Object> updateMap)throws Exception{
		SaveCatalogPackageListCall saveCatalogPackageListCall = new SaveCatalogPackageListCall();
		int packageId1 = saveCatalogPackageListCall.callAndGetReturnData(MapUtil.hashMap("ProductPackageList[0]->SubCatalogName","测试组合002测试组合002"))
								.getJSONObject("Data").getJSONArray("SubCatalogIdList").getInt(0);
		
		
		int packageId2 = saveCatalogPackageListCall.callAndGetReturnData(MapUtil.hashMap("ProductPackageList[0]->SubCatalogName","测试组合001测试组合001"))
				.getJSONObject("Data").getJSONArray("SubCatalogIdList").getInt(0);
		
		
		JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc12.json");	
		if (updateMap==null){updateMap = new HashMap<>();}
		updateMap.put("UserID", sellerId);
		updateMap.put("LoginID", sellerName);
		updateMap.put("Product->Catalogs[0]->SubCatalogId", new JSONArray(Arrays.asList(packageId1,packageId2)));
		updateMap.put("Product->Catalogs[0]->IsPackage", true);
		JsonBeanHelper.updateJsonBean(addProductBean, updateMap);
		return SellerProductCallService.addNewProduct(addProductBean);
	}
	
	
	
	
	/***
	 * 发布商品为立即上架
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProductOnSale(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 0);
		map.put("Product->ProductName",
				"自动化测试_立即上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);
	}

	/***
	 * 发布商品为不上架
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProductNotOnSale(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 2);
		map.put("Product->ProductName",
				"自动化测试_不上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);
	}

	/***
	 * 发布商品
	 * @param fileName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProduct(Map<String, Object> updateMap)
			throws Exception {
		JSONObject addProductBean = JsonBeanHelper
				.getJsonBean(JsonBeanFile.AddNewProductTpl);
		JsonBeanHelper.updateJsonBean(addProductBean, updateMap);
		return addNewProduct(addProductBean);
	}

	public static JSONObject addNewProduct(JSONObject jsonbean)
			throws Exception {
		return new AddNewSellerProductCall().callAndGetReturnData(jsonbean);
	}

	/***
	 * 批量下架商品
	 * @param fileName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject batchSetProductOffSale(String productId,
			int sellerId) throws Exception {
		List<String> productidList = new ArrayList<>();
		productidList.add(productId);
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("ProductIds", new JSONArray(productidList));
		requestMap.put("UserId", sellerId);
		JSONObject result = new BatchSetProductOffSaleCall()
				.callAndGetReturnData(requestMap);
		return result;
	}

	
	public static JSONObject batchSetProductOnSale(String productId,
			int sellerId) throws Exception {
		List<String> productidList = new ArrayList<>();
		productidList.add(productId);
		Map<String, Object> requestMap = new HashMap<String, Object>();
		requestMap.put("ProductIds", new JSONArray(productidList));
		requestMap.put("UserId", sellerId);
		JSONObject result = new BatchSetProductOnSaleCall()
				.callAndGetReturnData(requestMap);
		return result;
	}
	
	
	/**
	 * 发布FBX商品（单规格）
	 * @param updateMap 
	 * @return 返回商品ID
	 * @throws Exception
	 */
	public static String addFBXProduct(Map<String, Object> updateMap)
			throws Exception {
		JSONObject addFBXProductBean = JsonBeanHelper
				.getJsonBean("com.ymatou.iapi.sellerproduct/AddFbxProductCall/addfbxproductcalltpl.json");
		JsonBeanHelper.updateJsonBean(addFBXProductBean, updateMap);
		String sProductID = new AddFbxProductCall()
				.callAndGetReturnData(addFBXProductBean).getJSONObject("Data")
				.getString("ProductID");
		return sProductID;
	}

	/**
	 * 编辑商品
	 * @param jsonbean
	 * @return
	 * @throws Exception
	 */
	public static JSONObject changeNewProduct(JSONObject jsonbean)
			throws Exception {
		ChangeNewProductInfoCall changeNewProductInfoCall = new ChangeNewProductInfoCall();
		changeNewProductInfoCall.setData(jsonbean);
		changeNewProductInfoCall.callService();
		return new JSONObject(changeNewProductInfoCall.getReturnData());
	}

	/***]
	 * 添加商品到直播
	 * @param userId
	 * @param liveId
	 * @param productId
	 * @return
	 * @throws ClientProtocolException
	 * @throws JSONException
	 * @throws IOException
	 */
	public static JSONObject addProductInLive(int userId, int liveId,
			String productId) throws ClientProtocolException, JSONException,
			IOException {
		List<String> productIdsList = new ArrayList<String>();
		productIdsList.add(productId);
		JSONObject ret = addProductsInLive(userId, liveId, productIdsList);
		
		
		/*if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			try {
				Map<String,Object> liveMap = new LivesWapper().getByActivityId(liveId);
				new LiveProductsWapper().update(MapUtil.hashMap("sid", userId, "lid", liveId),
						MapUtil.hashMap("start", (Date)liveMap.get("start"), "end", (Date)liveMap.get("end")));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		return ret;
	}

	/***
	 * 添加商品组到直播
	 * @param userId
	 * @param liveId
	 * @param productIdsList
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static JSONObject addProductsInLive(int userId, int liveId,
			List<String> productIdsList) throws JSONException,
			ClientProtocolException, IOException {

		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("UserId", userId);
		updateMap.put("ActivityId", liveId);
		updateMap.put("ProductIds", new JSONArray(productIdsList.toString()));

		JSONObject jsonObject = JsonBeanHelper
				.getJsonBean(JsonBeanFile.AddProductInLivesTpl);
		JsonBeanHelper.updateJsonBean(jsonObject, updateMap);

		JSONObject ret = new AddProductInLivesCall().callAndGetReturnData(jsonObject);
		
		if (YmtMongoDriverFactroy.isEsCheck()){
			productIdsList.forEach(productId->new EsCall().callAndGetReturnData(0,productId,"UpdateLiveTimeForEs"));
		}
		
		return ret;

	}

	/***
	 * 在直播中，商品暂停销售
	 * @param userId
	 * @param liveId
	 * @param productId
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static JSONObject suspendSaleProductInLive(int userId, int liveId,
			String productId) throws Exception {

		List<String> productIdsList = new ArrayList<String>();
		productIdsList.add(productId);

		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("UserId", userId);
		updateMap.put("ActivityId", liveId);
		updateMap.put("ProductIds", new JSONArray(productIdsList.toString()));

		return  new ActivityProductSuspendSaleCall().callAndGetReturnData(updateMap);
	}
	
	
	public static Map<String,JSONObject> removeProductFromLive(int userId, int liveId,
			List<String> productIds) throws Exception {
		
		Map<String,JSONObject> ret = new HashMap<>();
		
		productIds.forEach(x->{
			ret.put(x, new RemoveProductFromLiveCall().callAndGetReturnData(MapUtil.hashMap("ProductId",x,"LiveId", liveId,"UserId", userId)));
		});
		return  ret;
	}
	
	

	/***
	 * 在直播中，商品开始销售
	 * @param userId
	 * @param liveId
	 * @param productId
	 * @return
	 * @throws JSONException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static JSONObject startSaleProductInLive(int userId, int liveId,
			String productId) throws Exception {
		List<String> productIdsList = new ArrayList<String>();
		productIdsList.add(productId);

		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("UserId", userId);
		updateMap.put("ActivityId", liveId);
		updateMap.put("ProductIds", new JSONArray(productIdsList.toString()));

		return new ActivityProductStartSaleCall()
				.callAndGetReturnData(updateMap);
	}

	/***
	 * 发布商品并申请参加活动
	 * @param activityId
	 * @return
	 */
	public static String addNewProductAndApproveActivity(int sellerId,
			String sellerName, String adminName, String adminPswd,
			String activityId, Map<String, Object> productUpdateMap) {
		try {
			//1.添加商品 -不上架
			JSONObject productReqObject = SellerProductCallService
					.addNewProductNotOnSale(sellerId, sellerName,
							productUpdateMap);
			Logger.verifyEquals(200, productReqObject.getInt("Code"),
					"响应报文-返回码");

			//获取返回报文的ProductID值
			String productID = productReqObject.getJSONObject("Data")
					.getString("ProductID");
			Logger.verifyNotNull(productID, "响应报文-商品ID");

			/*//获取Catalogs id - SQL Ymt_Catalogs integratedproduct库
			String catalogsID = new YmtCatalogsIWapper().selectCatalogsByProductId(productID).get(0).getsCatalogId();

			
			//todo 活动id
			//2.参加活动 
			JSONObject applyActivityRequest = ActivityCallService.applyProductInActivity(sellerId, productID, catalogsID, activityId);
			Logger.verifyEquals(200,applyActivityRequest.getInt("Code"), "响应报文-返回码");
			
			//查找productInActivityId
			YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();	
			YmtProductsInActivity productsInActivity = ymtProductsInActivityWapper.selectByProductId(productID);
			int productInActivityId = productsInActivity.getIproductinactivityid();
			
			//3. 开始活动二审
			//3.2  审核通过
			JSONObject approveProductRequest = AdminCallService.approveProductInActivity(adminName,adminPswd,String.valueOf(productInActivityId));		
			
			//验证审核通过
			String msgStr = approveProductRequest.getString("Success").equals("true")?"活动审核通过":"活动审核不通过";
			Logger.comment(msgStr);*/

			approveActivity(sellerId, adminName, adminPswd, activityId,
					productID);

			return productID;
		} catch (Exception e) {
			Logger.fail(e);
		}
		return null;

	}

	//申请参加活动
	/*	public static void approveActivity(int sellerId,String adminName,String adminPswd,String activityId,String productID) throws Exception{
			//获取Catalogs id - SQL Ymt_Catalogs integratedproduct库
			String catalogsID = new YmtCatalogsIWapper().selectCatalogsByProductId(productID).get(0).getsCatalogId();

		
			//todo 活动id
			//2.参加活动 
			JSONObject applyActivityRequest = ActivityCallService.applyProductInActivity(sellerId, productID, catalogsID, activityId);
			//Logger.verifyEquals(200,applyActivityRequest.getInt("Code"), "响应报文-返回码");
			
			//查找productInActivityId
			YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();	
			YmtProductsInActivity productsInActivity = ymtProductsInActivityWapper.selectByProductId(productID);
			int productInActivityId = productsInActivity.getIproductinactivityid();
			
			//3. 开始活动二审
			//3.2  审核通过
			JSONObject approveProductRequest = AdminCallService.approveProductInActivity(adminName,adminPswd,String.valueOf(productInActivityId));		
			
			//验证审核通过
			String msgStr = approveProductRequest.getString("Success").equals("true")?"活动审核通过":"活动审核不通过";
			Logger.comment(msgStr);
		}
		*/

	//申请参加活动 并审核通过  
	//默认商品所有规格都参加活动
	public static void approveActivity(int sellerId, String adminName,
			String adminPswd, String activityId, String productID)
			throws Exception {
		//todo 活动id
		//2.参加活动 
		ApplyActivityCall.applyProductInActivity(sellerId, productID,
				Integer.parseInt(activityId), new HashMap<String, Object>());
		//Logger.verifyEquals(200,applyActivityRequest.getInt("Code"), "响应报文-返回码");

		//查找productInActivityId
		YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();
		YmtProductsInActivity productsInActivity = ymtProductsInActivityWapper
				.selectByProductIdAndActivityId(productID,
						Integer.parseInt(activityId));
		int productInActivityId = productsInActivity.getIproductinactivityid();

		//3. 开始活动二审
		//3.2  审核通过
		YMTDateUtil.waitTime(2);
		JSONObject approveProductRequest = AdminCallService
				.approveProductInActivity(adminName, adminPswd,
						String.valueOf(productInActivityId));

		//验证审核通过
		/*String msgStr = approveProductRequest.getString("Success").equals("true")?"活动审核通过":"活动审核不通过";
		Logger.comment(msgStr);*/
	}

	/**
	 * SQL断言商品的首次露出时间
	 * @param type 1当前操作时间（场景：立即上架，添加到进行中的直播）
	 * @param type 2 商品的开始上架时间（场景：定时上架）
	 * @param type 3 商品在直播中的开始时间的最小值（场景：商品加入即将开始直播）
	 * @param type 4 2099-12-31（场景：发布但不上架）
	 * @return true or false
	 * @throws Exception
	 */
	public static void checkSqlListingTime(String productID, int type)
			throws InterruptedException {
		//SQL取值
		//Ymt_Products
		/*YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
		List<YmtProductsI> rm1 = ymtProductsIWapper
				.selectProductByProductId(productID);
		if (type == 1) {
			Logger.comment("期望首次露出时间为发布操作的时间，误差不超过180秒");
			AssertService.assertTime(YMTDateUtil.getDate(), rm1.get(0)
					.getdListingTime(), 180);
				    	Logger.comment("当前操作时间为："+YMTDateUtil.getDate());
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("误差在30秒以内，验证通过");

			Logger.comment("期望新品结束时间为首次露出时间加七天");
			AssertService.assertTime(rm1.get(0).getdListingTime(), rm1.get(0)
					.getdNewEndTime(), 604800);
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("SQL中新品结束时间为："+rm1.get(0).getdNewEndTime());
				    	Logger.comment("相差7天，验证通过");
		} else if (type == 2) {
			Logger.comment("期望首次露出时间为商品自身的上架时间");
			AssertService.assertTime(rm1.get(0).getValidStart(), rm1.get(0)
					.getdListingTime(), 0);
				    	Logger.comment("商品本身的上架时间为："+rm1.get(0).getValidStart());
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("首次露出时间与商品自身的上架时间相等，验证通过");

			Logger.comment("期望新品结束时间为首次露出时间加七天");
			AssertService.assertTime(rm1.get(0).getdListingTime(), rm1.get(0)
					.getdNewEndTime(), 604800);
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("SQL中新品结束时间为："+rm1.get(0).getdNewEndTime());
				    	Logger.comment("相差7天，验证通过");
		} else if (type == 3) {
			Logger.comment("期望首次露出时间为商品在直播中未开始的最早销售时间");
			YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
			List<YmtProductsInLive> ymtProductsInLive = ymtProductsInLiveWapper
					.selectInSonLiveByProductIdOrderBydStartTime(productID);
			if (ymtProductsInLive.size() == 0) {
				Logger.comment("未取到该商品在直播中未开始销售的记录，请确认问题");
			} else {
				AssertService.assertTime(ymtProductsInLive.get(0)
						.getDstarttime(), rm1.get(0).getdListingTime(), 0);
			}

				    	Logger.comment("商品在直播中未开始销售的最早时间为："+ymtProductsInLive.get(0).getDstarttime());
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("首次露出时间与商品在直播中未开始的最早销售时间相等，验证通过");

			Logger.comment("期望新品结束时间为首次露出时间加七天");
			AssertService.assertTime(rm1.get(0).getdListingTime(), rm1.get(0)
					.getdNewEndTime(), 604800);
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("SQL中新品结束时间为："+rm1.get(0).getdNewEndTime());
				    	Logger.comment("相差7天，验证通过");
		} else if (type == 4) {
			Logger.comment("期望首次露出时间为2099-12-31 00:00:00.000");
			AssertService.assertTime(YMTDateUtil.parseDate(
					"2099-12-31 00:00:00.000", YMTDateUtil.YMDHMSS), rm1.get(0)
					.getdListingTime(), 0);
				    	Logger.comment("期待的首次露出时间为：2099-12-31 00:00:00.000");
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("首次露出时间与期望值一致，验证通过");

			Logger.comment("期望新品结束时间为首次露出时间加七天");
			AssertService.assertTime(rm1.get(0).getdListingTime(), rm1.get(0)
					.getdNewEndTime(), 604800);
				    	Logger.comment("SQL中首次露出时间为："+rm1.get(0).getdListingTime());
				    	Logger.comment("SQL中新品结束时间为："+rm1.get(0).getdNewEndTime());
				    	Logger.comment("相差7天，验证通过");
		} else {
			System.out.println("请根据具体场景输入type");
		}*/
	}

	/**
	 * 取jsonObjectBean的实例
	 * JSONObject jsonObjectBean  = new AddNewSellerProductCall().callAndGetReturnData(jsonbean); 
	 * 
	 * 根据报文和sku返回对应的Catalog的报文信息
	 * @param jsonObjectBean 完整的返回报文+请求报文
	 * @param sku 商品sku
	 * @return 返回对应的Catalog的报文信息
	 * @throws Exception
	 */
	public static JSONObject returnOneCatalogsbyJsonbean(
			JSONObject jsonObjectBean, String sku) throws Exception {
		try {

			JSONArray sourceCatalogList = jsonObjectBean
					.getJSONObject("JsonBeanRequest").getJSONObject("Product")
					.getJSONArray("Catalogs");

			JSONObject jCatalogList = null;
			for (int i = 0; i < sourceCatalogList.length(); i++) {
				if (sku.equals(sourceCatalogList.getJSONObject(i).getString(
						"SKU"))) {
					jCatalogList = sourceCatalogList.getJSONObject(i);
				}
			}
			return jCatalogList;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 循环对比2个Map
	 * @param filed1 期待结果
	 * @param filed2 实际结果
	 * @throws Exception
	 * 
	 * 		HashMap<String, Object> param = new HashMap<>();
			param.put("sProductId", 123);
			param.put("sProduct", "name");
		
			YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();           
	        List<Map> rm = ymtProductsIWapper.selectProductByProductIdforMap("6cd2c583-314e-4f7e-964f-0f41eaae37e5");
	        //取出第n条，转换为HashMap
	        HashMap<String, Object> ttt = (HashMap<String, Object>) rm.get(0);
	        
	        SellerProductCallService.checkAllSQLverifyEquals(param, ttt);
	 */
	public static void checkAllSQLverifyEquals(HashMap<String, Object> filed1,
			HashMap<String, Object> filed2) throws Exception {
		try {

			for (Map.Entry<String, Object> entry : filed1.entrySet()) {
				String key = entry.getKey();
				Object value1 = entry.getValue();
				Object value2 = filed2.get(key);
				Logger.verifyEquals(value1, value2, key + "对比");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发布一个6天前自动上架的商品
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProducthistory(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 1);
		map.put("Product->AutoRefresh", true);
		map.put("Product->ProductName",
				"自动化测试_定时上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		//定时为6天前上架的商品
		Calendar c = Calendar.getInstance();
		c.add(Calendar.HOUR, -145);
		map.put("Product->ValidStart", sdf.format(c.getTime()));

		c.add(Calendar.HOUR, 23);
		map.put("Product->ValidEnd", sdf.format(c.getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);

	}

	/**
	 * 发布一个10天前自动上架的商品
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProduct10dayago(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 1);
		map.put("Product->AutoRefresh", true);
		map.put("Product->ProductName",
				"自动化测试_定时上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		//设为为过去10天前发布的商品
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -10);
		map.put("Product->ValidStart", sdf.format(c.getTime()));

		c.add(Calendar.DAY_OF_MONTH, -3);
		map.put("Product->ValidEnd", sdf.format(c.getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);

	}

	/**
	 * 发布一个5天前自动上架的商品
	 * @param sellerId
	 * @param sellerName
	 * @param updateMap
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addNewProduct5dayago(int sellerId,
			String sellerName, Map<String, Object> updateMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("UserID", sellerId);
		map.put("LoginID", sellerName);

		map.put("Product->OnSaleType", 1);
		map.put("Product->AutoRefresh", true);
		map.put("Product->ProductName",
				"自动化测试_定时上架商品 "
						+ sdfForName.format(Calendar.getInstance().getTime()));

		//设为为过去5天前发布的商品
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_MONTH, -5);
		map.put("Product->ValidStart", sdf.format(c.getTime()));

		c.add(Calendar.DAY_OF_MONTH, 2);
		map.put("Product->ValidEnd", sdf.format(c.getTime()));

		if (updateMap != null) {
			map.putAll(updateMap);
		}

		return addNewProduct(map);

	}

	/***
	 * 根据三级目录id, 获取一级目录id，中文名，二级目录id，中文名，三级目录id，中文名
	 * @param thirdCategoryId
	 * @return
	 * @throws InterruptedException
	 */
	public static CatalogLevelBean getProductCategroyByThirdCategoryId(
			int thirdCategoryId) throws InterruptedException {
		YmtProductCategoryWapper ymtProductCategoryWapper = new YmtProductCategoryWapper();

		Map<String, Object> ret = ymtProductCategoryWapper
				.getProductCategoryByCategoryId(thirdCategoryId).get(0);
		String ThirdCategoryName = ret.get("sCategory").toString();
		int CategoryId = Integer
				.parseInt(ret.get("iMasterCategory").toString());

		ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(
				CategoryId).get(0);
		String CategoryName = ret.get("sCategory").toString();
		int MasterCategoryId = Integer.parseInt(ret.get("iMasterCategory")
				.toString());

		ret = ymtProductCategoryWapper.getProductCategoryByCategoryId(
				MasterCategoryId).get(0);
		String MasterCategoryName = ret.get("sCategory").toString();

		CatalogLevelBean catalogLevelBean = new CatalogLevelBean(
				MasterCategoryName, MasterCategoryId, CategoryName, CategoryId,
				ThirdCategoryName, thirdCategoryId);

		return catalogLevelBean;

	}

	public static BrandBean getBrandInfo(int brandId)
			throws InterruptedException {
		Map<String, Object> productBrand = new YmtProductBrandWapper()
				.getProductBrandByBrandId(brandId).get(0);

		String brandName = productBrand.get("sBrand").toString();
		String brandEnName = productBrand.get("sBrandEn").toString();
		BrandBean brandBean = new BrandBean(brandId, brandName, brandEnName);
		return brandBean;
	}

	public static BrandBean getBrandInfoByProdId(String prodId)
			throws InterruptedException {
		//品牌英文名取自于商品表sbrand,中文名取自于品牌表
		YmtProductsI ymtProductsI = new YmtProductsIWapper()
				.selectProductByProductId(prodId).get(0);
		int brandId = ymtProductsI.getiBrandId();
		String brandEnName = ymtProductsI.getsBrand();
		String brandName = "";
		if (brandId == 0) {
			//自定义品牌 没有中文名
		} else {
			//标准品牌 
			Map<String, Object> productBrand = new YmtProductBrandWapper()
					.getProductBrandByBrandId(brandId).get(0);
			brandName = productBrand.get("sBrand").toString();
		}
		BrandBean brandBean = new BrandBean(brandId, brandName, brandEnName);
		return brandBean;
	}

	/**
	 * 
	 * @param productId
	 * @param modifyPicList
	 * @throws Exception
	 */
	public static void checkSQLAndMongo_ModifyPicture(String productId,
			List<String> modifyPicList) throws Exception {
		//check SQL
		List<Map> retList = new YmtProductPictureWapper()
				.selectByProductId(productId);
		Logger.verifyEquals(true, retList.size() >= 2, "SQL-ProductPicture记录");

		
		List<String> picInSql = retList.stream().filter(x->Integer.parseInt(x.get("iAction").toString())>-1).map(y->y.get("sOriUrl").toString()).collect(Collectors.toList());
		
		
		AssertService.checkArray(modifyPicList, picInSql);


		if (YmtMongoDriverFactroy.isNewMongoCheck()) {
			Map<String, Object> productDetailModelBean = new ProductDetailModelWapper()
					.getProductId(productId);
			JSONArray picArray = new JSONArray(productDetailModelBean.get(
					"PicList").toString());
			Logger.verifyEquals(modifyPicList.size(), picArray.length(),
					"Mongo-ProductDetailModel picList个数");
			for (String urlStr : modifyPicList) {
				Logger.verifyEquals(true, picArray.toString().contains(urlStr),
						"Mongo-ProductDetailModel picList");
			}

		}

	}

	/***
	 * 检查新品露出时间
	 * @param productId 商品id
	 * @param expectedDate 期待时间，可为空， 与sql值比较
	 * @throws Exception
	 */
	public static void checkListingTime(String productId, Date expectedDate)
			throws Exception {
		/*Logger.comment("商品首次露出时间检查");

		YmtProductsI ymtProductsI = new YmtProductsIWapper()
				.selectProductByProductId(productId).get(0);
		Date listingTime = ymtProductsI.getdListingTime();
		Date newEndTime = ymtProductsI.getdNewEndTime();
		boolean isNew = ymtProductsI.getIsNew() == 0 ? false : true;

		Logger.verifyEquals(YMTDateUtil.diffMinute(newEndTime, listingTime),
				7 * 24 * 60, "新品开始时间和结束时间 相差7天");
		if (expectedDate != null) {
			AssertService.assertTime(expectedDate, listingTime, 60);
		}

		if (YmtMongoDriverFactroy.isOldMongoCheck()) {
			//ProductBasicInfo
			Logger.comment("检查ProductBasicInfo 表中时间和isNew");
			Map<String, Object> productBasicMap = new ProductBasicInfoWapper()
					.getByProductId(productId);
			AssertService.assertTime(listingTime,
					(Date) productBasicMap.get("NewStartTime"), 1);
			AssertService.assertTime(newEndTime,
					(Date) productBasicMap.get("NewEndTime"), 1);
			Logger.verifyEquals(isNew, Boolean.parseBoolean(productBasicMap
					.get("IsNew").toString()), "ProductBasicInfo - isNew");

		}

		if (YmtMongoDriverFactroy.isNewMongoCheck()) {
			Date listingTimePre = new YmtProductsIWapper()
					.selectProductByProductId(productId).get(0)
					.getdListingTime();
			boolean ret = false;

			int tryTime = 0;
			while (ret == false && tryTime < 10) {
				ret = YmtMongoDriverFactroy.isUpdate("ProductDetailModel",
						MapUtil.hashMap("ProductId", productId),
						MapUtil.hashMap("NewStartTime", listingTimePre));
				YMTDateUtil.waitTime(2);
				tryTime = tryTime + 1;
			}

			if (ret) {

				//productDetailModel
				Logger.comment("检查ProductDetailModel 表中时间和isNew");
				Map<String, Object> productDetailMap = new ProductDetailModelWapper()
						.getProductId(productId);
				AssertService.assertTime(listingTime,
						(Date) productDetailMap.get("NewStartTime"), 1);
				AssertService.assertTime(newEndTime,
						(Date) productDetailMap.get("NewEndTime"), 1);
				Logger.verifyEquals(isNew,
						Boolean.parseBoolean(productDetailMap.get("IsNew")
								.toString()), "ProductDetailModel - isNew");

				//productListing
				Logger.comment("检查productListingModel 表中时间和isNew");
				Map<String, Object> productListingMap = new ProductListingModelWapper()
						.getProductId(productId);
				AssertService.assertTime(listingTime,
						(Date) productListingMap.get("NewStartTime"), 1);
				AssertService.assertTime(newEndTime,
						(Date) productListingMap.get("NewEndTime"), 1);
				Logger.verifyEquals(isNew,
						Boolean.parseBoolean(productListingMap.get("IsNew")
								.toString()), "ProductDetailModel - isNew");
			} else {
				Logger.verifyEquals(false, true,
						"checkListingTime - time is not update");
			}

		}*/
	}

	/***
	 * 商品属性值检查
	 * 
	 * 
	 * @param productId
	 * @param tgtPropertyArray - [{"PropertyValue":["莱卡"],"PropertyId":71},{"PropertyValue":["青少年"],"PropertyId":9}]
	 * @throws Exception
	 */
	public static void checkProdProperty(String productId,
			JSONArray tgtPropertyArray) throws Exception {
		SpuPropertyWapper spuPropertyWapper = new SpuPropertyWapper();

		//check Sql
		List<Map<String, Object>> retsInSql = new YmtProductPropertyWapper()
				.selectByProdId(productId);
		Logger.verifyEquals(tgtPropertyArray.length(), retsInSql.size(),
				"sql 属性值记录比较");

		for (int i = 0; i < tgtPropertyArray.length(); i++) {
			String sPropertyId = tgtPropertyArray.getJSONObject(i).getString(
					"PropertyId");
			JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
					.getJSONArray("PropertyValue");
			List<String> propertyValueList = new ArrayList<>();
			for (int j = 0; j < propertyValue.length(); j++) {
				propertyValueList.add(propertyValue.getString(j));
			}

			Map<String, Object> retInSql = retsInSql
					.stream()
					.filter(ele -> ele.get("PropertyId").toString()
							.equals(sPropertyId)).findAny().orElse(null);

			if (retInSql == null) {
				Logger.verifyEquals(false, true, "Ymt_ProductProperty product:"
						+ productId + ",propertyid:" + sPropertyId + " 不存在");
			} else {
				JSONArray actValInSql = new JSONArray(Arrays.asList(retInSql
						.get("Value").toString().split(",")));
				AssertService.checkArray(actValInSql, propertyValue,
						"Ymt_ProductProperty value值检查");
			}
		}

		if (YmtMongoDriverFactroy.isNewMongoCheck()) {
			ProductDescExtraWapper productDescExtraWapper = new ProductDescExtraWapper();
			Logger.verifyEquals(1,
					productDescExtraWapper.getCountByProductId(productId),
					"ProductDescExtra 记录应该只有一条");
			Map<String, Object> mapInMgo = productDescExtraWapper
					.getByProductId(productId);
			if (tgtPropertyArray.length() == 0) {
				Logger.verifyIsNull(mapInMgo.get("PropertyList"), "属性值应该不存在");
			} else {
				JSONArray propertyListArray = new JSONArray(mapInMgo.get(
						"PropertyList").toString());

				JSONArray tgtArray = new JSONArray();
				for (int i = 0; i < tgtPropertyArray.length(); i++) {
					int sPropertyId = tgtPropertyArray.getJSONObject(i).getInt(
							"PropertyId");
					String sPropertyName = spuPropertyWapper.selectById(
							sPropertyId).getName();

					JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
							.getJSONArray("PropertyValue");
					List<String> propertyValueList = new ArrayList<>();
					for (int j = 0; j < propertyValue.length(); j++) {
						propertyValueList
								.add(propertyValue.getString(j).trim());
					}

					JSONObject temp = new JSONObject();
					temp.put("Key", sPropertyName);
					String tmpVal = "";
					for (int k = 0; k < propertyValueList.size(); k++) {
						tmpVal = tmpVal + "," + propertyValueList.get(k);
					}
					if (tmpVal.startsWith(",")) {
						tmpVal = tmpVal.substring(1, tmpVal.length());
					}

					//temp.put("Value", propertyValueList.toString().replace("[", "").replace("]", "").trim());
					temp.put("Value", tmpVal);

					tgtArray.put(temp);
				}

				AssertService.checkArray(propertyListArray, tgtArray);
			}
		}

		if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
			ProductDescExtraNewWapper productDescExtraWapper = new ProductDescExtraNewWapper();
			Logger.verifyEquals(1,
					productDescExtraWapper.getCountByProductId(productId),
					"ProductDescExtraNewWapper 记录应该只有一条");
			Map<String, Object> mapInMgo = productDescExtraWapper
					.getByProductId(productId);
			if (tgtPropertyArray.length() == 0) {
				Logger.verifyEquals(0, new JSONArray(mapInMgo.get("props")
						.toString()).length(), "属性值应该不存在");
			} else {
				JSONArray propertyListArray = new JSONArray(mapInMgo.get(
						"props").toString());

				JSONArray tgtArray = new JSONArray();
				for (int i = 0; i < tgtPropertyArray.length(); i++) {
					int sPropertyId = tgtPropertyArray.getJSONObject(i).getInt(
							"PropertyId");
					String sPropertyName = spuPropertyWapper.selectById(
							sPropertyId).getName();

					JSONArray propertyValue = tgtPropertyArray.getJSONObject(i)
							.getJSONArray("PropertyValue");
					List<String> propertyValueList = new ArrayList<>();
					for (int j = 0; j < propertyValue.length(); j++) {
						propertyValueList.add(propertyValue.getString(j));
					}

					JSONObject temp = new JSONObject();
					temp.put("key", sPropertyName);
					String tmpVal = "";
					for (int k = 0; k < propertyValueList.size(); k++) {
						tmpVal = tmpVal + "," + propertyValueList.get(k);
					}
					if (tmpVal.startsWith(",")) {
						tmpVal = tmpVal.substring(1, tmpVal.length());
					}

					//temp.put("Value", propertyValueList.toString().replace("[", "").replace("]", "").trim());
					temp.put("value", tmpVal);

					tgtArray.put(temp);
				}

				AssertService.checkArray(propertyListArray, tgtArray);
			}

		}

	}

	public static void checkTemplateWithProd(String productId,
			List<ProdTplBean> prodTplBeanList) throws Exception {
		boolean isHasProd = (productId != null && !productId.equals(""));

		//check Sql template
		YmtProductDescExtraWapper ymtProductDescExtraWapper = new YmtProductDescExtraWapper();
		prodTplBeanList.forEach(ele -> {
			try {
				Logger.comment("YmtProductDescExtra check");
				YmtProductDescExtra datainSql = ymtProductDescExtraWapper
						.selectByTemplateId(ele.getTemplateId());
				Map<String, Object> mapInSql = MapUtil.pojoToMap(datainSql);

				if (mapInSql.get("picUrls") == null
						|| mapInSql.get("picUrls").toString().equals("")) {
					Logger.verifyEquals(0, ele.getPicUrls().size(),
							"Template 图片应该不存在");
				} else {
					List<String> tmpPicInSql = Arrays.asList(mapInSql
							.get("picUrls").toString().split(","));
					AssertService.checkArray(tmpPicInSql, ele.getPicUrls());
				}

				Map<String, Object> requestMap = MapUtil.hashMap();
				requestMap.put("ID", ele.getTemplateId());
				requestMap.put("sellerId", ele.getTemplateSellerId());
				requestMap.put("templateName", ele.getTemplateName());
				requestMap.put("description", ele.getTemplateDesc());
				requestMap.put("templateType", ele.getTemplateType());
				AssertService.assertResultEqual(requestMap, mapInSql);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		});

		if (isHasProd) {
			int thirdCategoryId = new YmtProductsIWapper()
					.selectProductByProductId(productId).get(0)
					.getiThirdCategoryId();
			@SuppressWarnings("unchecked")
			Map<String, Object> ret = new YmtProductCategoryWapper()
					.getProductCategoryByCategoryId(thirdCategoryId).get(0);

			String measurePicStr = ret.get("MeasurePic") != null ? ret.get(
					"MeasurePic").toString() : "";

			/*	ProdTplBean prodTplBeanTmp = prodTplBeanList.stream().filter(ele->ele.getTemplateType()==1).findFirst().orElse(null);
				if (prodTplBeanTmp!=null){
					List<String> picUrls = prodTplBeanTmp.getPicUrls();
					//if (!measurePicStr.equals("")){picUrls.add(measurePicStr);}
				}*/

			//1 check Sql product template info 
			List<Map<String, Object>> retMaps = new YmtProductDescMapWapper()
					.selectByProdId(productId);
			Logger.verifyEquals(1, retMaps.size(), "YmtProductDesc 记录应该只有一条");
			Map<String, Object> retMap = retMaps.get(0);
			prodTplBeanList.forEach(ele -> {
				Logger.comment("YmtProductDescMapW check");
				if (ele.getTemplateId() != 0) {
					switch (ele.getTemplateType()) {
						case 1 :
							Logger.verifyEquals(
									ele.getTemplateId(),
									Integer.parseInt(retMap.get(
											"SizeTemplateId").toString()),
									"YmtProductDescMapWapper SizeTemplateId");
							break;
						case 2 :
							Logger.verifyEquals(ele.getTemplateId(), Integer
									.parseInt(retMap.get("BuyerNoticeId")
											.toString()),
									"YmtProductDescMapWapper BuyerNoticeId");
							break;
						case 3 :
							Logger.verifyEquals(
									ele.getTemplateId(),
									Integer.parseInt(retMap.get(
											"SellerServiceId").toString()),
									"YmtProductDescMapWapper SellerServiceId");
							break;
						default :
							Logger.verifyEquals(
									false,
									true,
									"模板类型  应该在1,2,3之中。实际为:"
											+ ele.getTemplateType());
							break;
					}

				}
			});

			//check new Mongo product template info 
			if (YmtMongoDriverFactroy.isNewMongoCheck()) {
				//2 productDescExtra
				ProductDescExtraWapper productDescExtraWapper = new ProductDescExtraWapper();
				Logger.verifyEquals(1,
						productDescExtraWapper.getCountByProductId(productId),
						"ProductDescExtra 记录应该只有一条");
				Map<String, Object> mapInMgo = productDescExtraWapper
						.getByProductId(productId);

				prodTplBeanList.forEach(ele -> {
					try {
						if (ele.getTemplateId() != 0) {
							if (ele.getTemplateType() == 1) {
								JSONArray jsonArray = new JSONArray(ele
										.getPicUrls());
								if (!measurePicStr.equals("")) {
									jsonArray.put(measurePicStr);
								}
								AssertService.checkArray(
										jsonArray,
										new JSONArray(mapInMgo.get(
												"SizePicList").toString()));
							}

							if (ele.getTemplateType() == 2) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("NoticeText"),
										"ProductDescExtra noticeText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get(
												"NoticePicList").toString()));
							}

							if (ele.getTemplateType() == 3) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("SellerIntroText"),
										"ProductDescExtra SellerIntroText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get(
												"SellerIntroPicList")
												.toString()));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				});

				//1 product detail 
				JSONArray sizePicsInMgo = new JSONArray(
						new ProductDetailModelWapper().getProductId(productId)
								.get("SizePicList").toString());
				ProdTplBean prodTplBean = prodTplBeanList.stream()
						.filter(ele -> ele.getTemplateType() == 1).findFirst()
						.orElse(null);

				if (prodTplBean == null) {
					//没有size list
					Logger.verifyEquals(0, sizePicsInMgo.length(),
							"应该没有size pic list");
					Logger.verifyEquals(0,
							new JSONArray(mapInMgo.get("SizePicList")
									.toString()).length(), "应该没有size pic list");

				} else {
					JSONArray jsonArray = new JSONArray(
							prodTplBean.getPicUrls());
					if (!measurePicStr.equals("")) {
						jsonArray.put(measurePicStr);
					}
					AssertService.checkArray(sizePicsInMgo, jsonArray,
							"ProductDetailMap-Size pic 比较");
				}
			}

			//check java new Mongo
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {
				//2 productDescExtra
				ProductDescExtraNewWapper productDescExtraWapper = new ProductDescExtraNewWapper();
				Logger.verifyEquals(1,
						productDescExtraWapper.getCountByProductId(productId),
						"ProductDescExtraNew 记录应该只有一条");
				Map<String, Object> mapInMgo = productDescExtraWapper
						.getByProductId(productId);

				prodTplBeanList.forEach(ele -> {
					try {
						if (ele.getTemplateId() != 0) {
							if (ele.getTemplateType() == 1) {
								JSONArray jsonArray = new JSONArray(ele
										.getPicUrls());
								if (!measurePicStr.equals("")) {
									jsonArray.put(measurePicStr);
								}
								AssertService.checkArray(jsonArray,
										new JSONArray(mapInMgo.get("sizepics")
												.toString()));
							}

							if (ele.getTemplateType() == 2) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("notice"),
										"ProductDescExtraNew noticeText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get("notipics")
												.toString()));
							}

							if (ele.getTemplateType() == 3) {
								Logger.verifyEquals(ele.getTemplateDesc(),
										mapInMgo.get("intro"),
										"ProductDescExtraNew SellerIntroText");
								AssertService.checkArray(
										new JSONArray(ele.getPicUrls()),
										new JSONArray(mapInMgo.get("intropics")
												.toString()));
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				});

				//1 product detail 
				ProdTplBean prodTplBean = prodTplBeanList.stream()
						.filter(ele -> ele.getTemplateType() == 1).findFirst()
						.orElse(null);
				if (prodTplBean == null) {
					//没有size   list
					Logger.verifyIsNull(
							new ProductsWapper().getByProductId(productId).get(
									"sizepics"), "应该没有size pic list");
					Logger.verifyIsNull(mapInMgo.get("sizepics"),
							"应该没有size pic list");
				} else {
					JSONArray jsonArray = new JSONArray(
							prodTplBean.getPicUrls());
					if (!measurePicStr.equals("")) {
						jsonArray.put(measurePicStr);
					}
					JSONArray sizePicsInMgo = new JSONArray(
							new ProductsWapper().getByProductId(productId)
									.get("sizepics").toString());
					AssertService.checkArray(sizePicsInMgo, jsonArray,
							"Product-Size pic 比较");
				}
			}

		}

	}

	public static void checkTemplate(List<ProdTplBean> prodTplBeanList)
			throws Exception {
		checkTemplateWithProd("", prodTplBeanList);
	}

	public static Map<String, Object> getThirdCategoryAndPropertyValue()
			throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("ThirdCategory", 1122);

		JSONObject property1 = new JSONObject();
		JSONArray PropertyValue1 = new JSONArray(Arrays.asList("莱卡"));
		property1.put("PropertyId", 71);
		property1.put("PropertyValue", PropertyValue1);

		JSONObject property2 = new JSONObject();
		JSONArray PropertyValue2 = new JSONArray(Arrays.asList("120mL"));
		property2.put("PropertyId", 60);
		property2.put("PropertyValue", PropertyValue2);

		map.put("PropertyList",
				new JSONArray(Arrays.asList(property1, property2)));

		return map;
	}

	public static Map<String, Object> getThirdCategoryAndPropertyValueUpdate()
			throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("ThirdCategory", 1123);

		/*		JSONObject property1 = new JSONObject();
				JSONArray PropertyValue1 = new JSONArray(Arrays.asList("酸奶"));
				property1.put("PropertyId", 90);
				property1.put("PropertyValue", PropertyValue1);*/

		JSONObject property2 = new JSONObject();
		JSONArray PropertyValue2 = new JSONArray(Arrays.asList("120"));
		property2.put("PropertyId", 8);
		property2.put("PropertyValue", PropertyValue2);

		JSONObject property3 = new JSONObject();
		JSONArray PropertyValue3 = new JSONArray(Arrays.asList("NB", "S"));
		property3.put("PropertyId", 88);
		property3.put("PropertyValue", PropertyValue3);

		map.put("PropertyList",
				new JSONArray(Arrays.asList(property2, property3)));

		return map;
	}

	public static Map<String, Object> getThirdCategoryAndPropertyValue2()
			throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("ThirdCategory", 1089);

		JSONObject property1 = new JSONObject();
		JSONArray PropertyValue1 = new JSONArray(Arrays.asList("酸奶"));
		property1.put("PropertyId", 90);
		property1.put("PropertyValue", PropertyValue1);

		JSONObject property2 = new JSONObject();
		JSONArray PropertyValue2 = new JSONArray(Arrays.asList("125mL"));
		property2.put("PropertyId", 60);
		property2.put("PropertyValue", PropertyValue2);

		map.put("PropertyList",
				new JSONArray(Arrays.asList(property1, property2)));

		return map;
	}

	/***
	 * 
	 * @param propertyList
	 * @param thirdCategoryId
	 * @param PropertyListHasVal
	 * @throws Exception
	 */
	public static void checkPropertyList(JSONArray propertyList,
			int thirdCategoryId, JSONArray PropertyListHasVal) throws Exception {
		List<SpuProperty> spuPropertyList = new SpuPropertyWapper()
				.selectByThirdcategoryidId(thirdCategoryId);
		Logger.verifyEquals(spuPropertyList.size(), propertyList.length(),
				"商品信息 返回校验 PropertyList record");

		for (int i = 0; i < propertyList.length(); i++) {
			JSONObject propertyJson = propertyList.getJSONObject(i);
			Integer PropertyId = propertyJson.getInt("PropertyId");
			SpuProperty spuProperty = spuPropertyList.stream()
					.filter(ele -> ele.getPropertyId().equals(PropertyId))
					.findFirst().orElse(null);

			Logger.verifyNotNull(spuProperty, "spuProperty propertyid:"
					+ PropertyId + " should be exists.");

			Map<String, Object> tgtMap = new HashMap<>();
			tgtMap.put("PropertyName", spuProperty.getName());
			tgtMap.put("PropertyValueType", spuProperty.getStyles());
			tgtMap.put("IsMultiple", spuProperty.getMultiSelect());

			//to do values check 
			propertyJson.remove("Values");
			AssertService.assertResultEqual(tgtMap,
					MapUtil.jsonToMap(propertyJson), "PropertyList id:"
							+ PropertyId + "check ");

			//property value check if has 
			JSONArray propertys = PropertyListHasVal;
			if (PropertyListHasVal != null && PropertyListHasVal.length() > 0) {
				boolean isHasVal = false;
				for (int j = 0; j < propertys.length(); j++) {
					if (propertys.getJSONObject(j).getInt("PropertyId") == PropertyId) {
						AssertService.checkArray((propertys.getJSONObject(j)
								.getJSONArray("PropertyValue")), propertyJson
								.getJSONArray("InputValues"));
						isHasVal = true;
						break;
					}
				}

				if (!isHasVal) {
					Logger.verifyEquals(0,
							propertyJson.getJSONArray("InputValues").length(),
							"InputValues should be empty");
				}
			}
		}

	}

	public static void main(String[] args) throws Exception {
		 CatalogLevelBean a = getProductCategroyByThirdCategoryId(1003);
			int cc=1;
			int bb=cc;
	}
}
